<template>
  <el-dialog title="添加用户"
             :visible.sync="isShow"
             @close="hideDialog">
    <el-form class="forms"
             ref="forms"
             label-width="100px"
             :rules="rules"
             :model="forms">
      <el-form-item class="inline"
                    label="用户姓名"
                    prop="name">
        <el-input v-model="forms.name"
                  size="small"
                  placeholder="请输入用户姓名"></el-input>
      </el-form-item>
      <el-form-item class="inline"
                    label="用户账号"
                    prop="username">
        <el-input v-model="forms.username"
                  size="small"
                  placeholder="请输入用户账号"></el-input>
      </el-form-item>
      <el-form-item class="inline"
                    label="密码"
                    prop="password">
        <el-input type="password"
                  v-model="forms.password"
                  size="small"
                  placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item class="inline"
                    label="确认密码"
                    prop="repassword">
        <el-input type="password"
                  v-model="repassword"
                  size="small"
                  placeholder="请输入确认密码"></el-input>
      </el-form-item>
      <el-form-item class="inline"
                    label="部门"
                    prop="deptId">
        <el-input v-model="deptName"
                  size="small"
                  disabled></el-input>
      </el-form-item>
      <el-form-item class="inline"
                    label="职位">
        <el-select v-model="forms.positionIds"
                   size="small"
                   placeholder="请选择职位"
                   loading-text="加载中..."
                   multiple
                   @remove-tag="removeTag">
          <el-option v-for="item in positions"
                     :key="item.positionId"
                     :label="item.positionName"
                     :value="item.positionId"
                     :disabled="item.disabled">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="inline"
                    label="工号"
                    prop="userCode">
        <el-input v-model="forms.userCode"
                  size="small"
                  placeholder="请输入工号"></el-input>
      </el-form-item>
      <el-form-item class="inline"
                    label="身份证号"
                    prop="identityCard">
        <el-input v-model="forms.identityCard"
                  size="small"
                  placeholder="请输入身份证号"></el-input>
      </el-form-item>
      <el-form-item class="inline"
                    label="手机号"
                    prop="moveTel">
        <el-input v-model="forms.moveTel"
                  size="small"
                  placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item class="inline"
                    label="Email"
                    prop="email">
        <el-input v-model="forms.email"
                  size="small"
                  placeholder="请输入Email"></el-input>
      </el-form-item>
      <el-form-item label="状态："
                    prop="status">
        <el-radio-group v-model="forms.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="2">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="角色：">
        <!-- <el-checkbox-group v-model="forms.roleList" style="display: inline-block">
          <el-checkbox v-for="item in roles" :label="item.id" :key="item.id">{{ item.roleName }}</el-checkbox>
        </el-checkbox-group> -->
        <el-transfer v-model="forms.roleList"
                     :data="roles"
                     :props="transferProps"
                     :titles="['可选角色', '已选角色']"></el-transfer>
      </el-form-item>
    </el-form>
    <div slot="footer"
         class="dialog-footer">
      <el-button @click="hideDialog('forms')">取 消</el-button>
      <el-button type="primary"
                 @click="handleSubmit()">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { roleList } from '@/apis/user/role';
import { fetchPositions, saveUser } from '@/apis/user/index';
export default {
    props: ['isShowDialog', 'deptId', 'deptName', 'positionId'],
    data () {
        var checkPassword = (rule, value, callback) => {
            if (this.repassword) {
                if (this.forms.password !== this.repassword) {
                    callback(new Error('两次密码输入不一致'));
                }
            } else {
                callback(new Error('请输入确认密码'));
            }
            callback();
        };
        // 校验手机
        var checkMoveTel = (rule, value, callback) => {
            if (value && !/^1[34578]\d{9}$/.test(value)) {
                return callback(new Error('请输入格式正确的手机号'));
            } else {
                callback();
            }
        };
        // 校验用户姓名
        var chckNames = (rule, value, callback) => {
            if (value && !/^[\u4e00-\u9fa5]+$/.test(value)) {
                return callback(new Error('仅限输入中文'));
            } else {
                callback();
            }
        };
        // 校验用户账号
        var checkUsername = (rule, value, callback) => {
            if (value && !/^[0-9a-zA-Z_]{1,}$/.test(value)) {
                return callback(new Error('仅限输入字母，数字，下划线'));
            } else {
                callback();
            }
        };
        // 校验邮箱
        var checkEmail = (rule, value, callback) => {
            if (value && !/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/.test(value)) {
                return callback(new Error('请输入格式正确的邮箱'));
            } else {
                callback();
            }
        };
        // 验证身份证号码是否合法
        var cardID = (rule, value, callback) => {
            if (value && !/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(value)) {
                return callback(new Error('请输入正确的身份证号码'));
            } else {
                callback();
            }
        };
        // 验证是否是数字
        var workNum = (rule, value, callback) => {
            if (value && !/^[0-9]*$/.test(value)) {
                return callback(new Error('请输入数字'));
            } else {
                callback();
            }
        };
        return {
            isShow: this.isShowDialog,
            positions: [],
            repassword: '',
            forms: {
                name: '',
                username: '',
                password: '',
                deptId: this.deptId,
                positionIds: [],
                userCode: '',
                identityCard: '',
                moveTel: '',
                email: '',
                status: 1,
                roleList: [],
                type: 1
            },
            rules: { // 表单验证规则
                name: [
                    { required: true, message: '请输入用户姓名', trigger: 'blur' },
                    { max: 10, message: '请输入长度不超过10位的字符', trigger: 'blur' },
                    { validator: chckNames, trigger: 'blur' }
                ],
                username: [
                    { required: true, message: '请输入用户账号', trigger: 'blur' },
                    { validator: checkUsername, trigger: 'blur' },
                    { max: 20, message: '请输入长度不超过20位的字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, message: '密码长度至少6个字符' }
                ],
                repassword: [
                    { required: true, validator: checkPassword, trigger: 'blur' },
                    { min: 6, message: '密码长度至少6个字符' }
                ],
                identityCard: [
                    { validator: cardID, trigger: 'blur' },
                    { min: 18, max: 18, message: '请输入长度为18位的字符', trigger: 'blur' }
                ],
                moveTel: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { validator: checkMoveTel, trigger: 'blur' }
                ],
                email: [
                    { validator: checkEmail, trigger: 'blur' }
                ],
                status: [
                    { required: true, message: '请选择状态', trigger: 'change' }
                ],
                userCode: [
                    { validator: workNum, trigger: 'blur' },
                    { min: 1, max: 20, message: '请输入长度不超过20位的数字', trigger: 'blur' }
                ]
            },
            roles: [], // 已选角色集合
            transferProps: { // 自定义角色绑定值
                key: 'id',
                label: 'roleName'
            }
        };
    },
    created () {
        roleList().then(data => { // 获取角色权限
            if (data.code === 100) {
                this.roles = data.data;
            } else {
                this.$message.error(data.message);
            }
        }).catch(() => {
            this.$message.error('roleList error');
        });

        // 获取部门职位
        fetchPositions(this.deptId).then(data => {
            if (data.code === 100) {
                this.positions = data.data;
                this.positions.forEach((item) => {
                    if (item.positionId === this.positionId) {
                        item.disabled = true;
                    }
                });
            } else {
                this.$message.error(data.message);
            }
        }).catch(() => {
            this.$message.error('获取部门职位异常');
        });
        // this.positionId.disabled = true
        this.positionId && this.forms.positionIds.push(this.positionId);
    },
    methods: {
        hideDialog (forms) {
            if (this.isShow) {
                // 重置表单
                this.$refs[forms].resetFields();
                this.deptName = '';
                this.positionName = '';
                this.repassword = '';
            }
            this.$emit('close');
        },
        removeTag (value) {
            if (this.positionId && value === this.positionId) {
                this.forms.positionIds.unshift(this.positionId);
                this.$message.error('当前职位不能被删除');
                return false;
            }
        },
        handleSubmit () {
            this.$refs.forms.validate(valid => {
                if (valid) {
                    saveUser(this.forms).then(data => {
                        if (data.code === 100) {
                            this.$message.success('添加成功');
                            this.$emit('saveDone');
                            this.$refs.forms.resetFields();
                            this.repassword = '';
                        } else if (data.code === -101) {
                            this.$message.error(data.message);
                        }
                    }).catch(() => {
                        this.$message.error('saveUser error');
                    });
                } else {
                    return false;
                }
            });
        }
    }
};
</script>
<style>
.selPosition {
  height: 32px;
}
.selPosition .el-input .el-input__inner {
  height: 32px !important;
}
</style>
